class DataCollection < ActiveRecord::Base
	include Comparable
	
	belongs_to :youth
	belongs_to :data_collection_status
	belongs_to :data_collection_type
	has_many :questionnaires, :dependent => :destroy
	
	after_create :create_questionnaires
	
	QUEST_NEVER_COMPLETED = "Never completed"
	QUEST_PROCESSED = "Processed"
	STATUS_NOT_STARTED = "Not started"
	STATUS_IN_PROGRESS = "In progress"
	STATUS_COMPLETED = "Completed"
	STATUS_ENDED_ALL_QUESTIONNAIRES_MISSING = "Ended (all questionnaires missing)"
	STATUS_ENDED_SOME_QUESTIONNAIRES_MISSING = "Ended (some questionnaires missing)"


	
	def calculate_status
		
		# Setting a "current status" for every questionnaire in this data collection
		quest_statuses = Array.new
		self.questionnaires.each do |q|
			if (q.questionnaire_events.size > 0)				
				status = :in_progress	# We have events, so the questionnaire is definately "in progress"
								
				q.questionnaire_events.each do |e|					
					if (e.questionnaire_event_type.name == QuestionnaireEventType.get_all_types[:RECIEVED_FOR_PROCESSING]) # TODO: Fix! (recieved)
						status = :processed
					elsif (e.questionnaire_event_type.name == QuestionnaireEventType.get_all_types[:NEVER_COMPLETED])
						status = :never_completed
					end
				end
			else
				status = :not_started	# No events exist, so no progress has been made with this questionnaire
			end
			
			quest_statuses.push(status)
		end
		
		
		# Combining all questionnaire statues into one "data collection status"
		if (quest_statuses.include?(:in_progress))
			return STATUS_IN_PROGRESS
		end
						
		if !(quest_statuses.include?(:never_completed) || quest_statuses.include?(:not_started)) # Only "processed" remain
			return STATUS_COMPLETED
		end
		
		if !(quest_statuses.include?(:processed) || quest_statuses.include?(:not_started)) # Only "never_completed" remain
			return STATUS_ENDED_ALL_QUESTIONNAIRES_MISSING
		end
		
		if (quest_statuses.include?(:processed) && quest_statuses.include?(:never_completed) && !quest_statuses.include?(:not_started))
			return STATUS_ENDED_SOME_QUESTIONNAIRES_MISSING
		end
		
		if ((quest_statuses.include?(:processed) || quest_statuses.include?(:never_completed)) && quest_statuses.include?(:not_started))
			return STATUS_IN_PROGRESS
		end
		
		return STATUS_NOT_STARTED
	end
	

	def self.get_statuses
		return [STATUS_NOT_STARTED, STATUS_IN_PROGRESS, STATUS_COMPLETED, STATUS_ENDED_SOME_QUESTIONNAIRES_MISSING, STATUS_ENDED_ALL_QUESTIONNAIRES_MISSING]
	end



	private
	
	def create_questionnaires
    QuestionnaireManager.create_questionnaires(self)
  end

end


